package com.qingxin.park.action;

import java.io.File;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qingxin.park.entity.FarmPark;
import com.qingxin.park.entity.ParkBlock;
import com.qingxin.park.entity.ParkBlockPlantView;
import com.qingxin.park.entity.ProRecord;
import com.qingxin.park.entity.ProRecordImgs;
import com.qingxin.park.entity.ProRecordMaterial;
import com.qingxin.park.entity.ProRecordView;
import com.qingxin.park.service.CropsService;
import com.qingxin.park.service.CropsjgService;
import com.qingxin.park.service.CropsyzService;
import com.qingxin.park.service.FarmParkService;
import com.qingxin.park.service.ParkBlockPlantService;
import com.qingxin.park.service.ParkBlockService;
import com.qingxin.park.service.ProRecordImgsService;
import com.qingxin.park.service.ProRecordMaterialService;
import com.qingxin.park.service.ProRecordService;
import com.qingxin.sys.action.BaseAction;
import com.qingxin.sys.entity.MyUploadFile;
import com.qingxin.sys.entity.MyUploadFileParam;
import com.qingxin.sys.entity.MyUploadFiles;
import com.qingxin.sys.mvc.PageParam;
import com.qingxin.sys.mvc.Pager;
import com.qingxin.sys.mvc.SysError;
import com.qingxin.sys.support.SystemCfg;
import com.qingxin.sys.utils.ExcelUtil;
import com.qingxin.sys.utils.StringUtils;


/**
 * 农事作业信息
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/proRecord")
public class ProRecordAction extends BaseAction {

	@Autowired
	private ParkBlockPlantService parkBlockPlantService;
	@Autowired
	private ProRecordService proRecordService;
	@Autowired
	private CropsService cropsService;
	
	@Autowired
	private ProRecordImgsService proRecordImgsService;
	@Autowired
	private ProRecordMaterialService proRecordMaterialService;
	
	@Autowired
	private CropsyzService cropsyzService;
	@Autowired
	private CropsjgService cropsjgService;
	
	@Autowired
	private FarmParkService farmParkService;
	@Autowired
	private ParkBlockService parkBlockService;
	
	/**
	 * 列表页
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/list.do", method=RequestMethod.GET)
	public String list(ModelMap model, HttpServletRequest request){
		return "trace/proRecord/proRecord_list";
	}
	
	@RequestMapping(value="/listyz.do", method=RequestMethod.GET)
	public String listyz(ModelMap model, HttpServletRequest request){
		return "trace/proRecord/proRecord_listyz";
	}
	
	@RequestMapping(value="/listjg.do", method=RequestMethod.GET)
	public String listjg(ModelMap model, HttpServletRequest request){
		return "trace/proRecord/proRecord_listjg";
	}
	
	
	@RequestMapping(value="/selectMaterial.do", method=RequestMethod.GET)
	public String selectMaterial(ModelMap model, HttpServletRequest request){
		return "trace/proRecord/proRecord_selectMaterial";
	}
	
	
	/**
	 * 列表分页数据
	 * @param leftdata
	 * @param datatype
	 * @param begin
	 * @param end
	 * @param pageParam
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/listdata.json" , method={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public Object listdata(String plantType, String leftdata, String datatype, @DateTimeFormat(pattern="yyyy-MM-dd")Date begin,
			@DateTimeFormat(pattern="yyyy-MM-dd")Date end, PageParam pageParam, HttpServletRequest request){
		String parkid = null;
		String blockid = null;
		if(SystemCfg.UI_DATATYPE_PARK.equals(datatype)){
			parkid = leftdata;
		}else if(SystemCfg.UI_DATATYPE_BLOCK.equals(datatype)){
			blockid = leftdata;
		}else{
			return new Pager();
		}
		
		Pager pager = proRecordService.list(plantType, parkid, blockid, begin, end, pageParam, getLoginUser(request));
		return pager;
	}
	
	
	
	/**
	 * 添加农事作业信息
	 * @param model
	 * @param leftdata
	 * @param datatype
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/add.do" , method=RequestMethod.GET)
	public String add(ModelMap model, String leftdata, String datatype, HttpServletRequest request){
		if(!SystemCfg.UI_DATATYPE_BLOCK.equals(datatype) || StringUtils.isEmpty(leftdata)){
			model.put("errormessage", "参数错误");
			return "sys/error/error";
		}
		model.put("blockid", leftdata);
		
		ParkBlockPlantView plant = parkBlockPlantService.getCurrentPlantView(leftdata);
		model.put("plant", plant);
		if(plant == null){
			ParkBlock parkBlock = parkBlockService.get(leftdata);
			if("1".equals(parkBlock.getBlockType())){
				model.put("errormessage", "该地块没有可用种植信息，请先到“生产档案 - 种植管理”模块添加种植信息");
			}else if("2".equals(parkBlock.getBlockType())){
				model.put("errormessage", "该地块没有可用养殖信息，请先到“生产档案 - 养殖管理”模块添加养殖信息");
			}else if("3".equals(parkBlock.getBlockType())){
				model.put("errormessage", "该地块没有可用加工信息，请先到“生产档案 - 加工管理”模块添加加工信息");
			}
			
			return "sys/error/error";
		}
		
		if("1".equals(plant.getPlantType())){
			String cropName = cropsService.getCropFullname(plant.getCropid());
			if(cropName == null){
				cropName = plant.getCropName();
			}
			model.put("cropName", cropName);
			
			return "trace/proRecord/proRecord_add";
		}else if("2".equals(plant.getPlantType())){
			String cropName = cropsyzService.getCropFullname(plant.getCropid());
			if(cropName == null){
				cropName = plant.getCropName();
			}
			model.put("cropName", cropName);
			
			return "trace/proRecord/proRecord_addyz";
		}else if("3".equals(plant.getPlantType())){
			String cropName = cropsjgService.getCropFullname(plant.getCropid());
			if(cropName == null){
				cropName = plant.getCropName();
			}
			model.put("cropName", cropName);
			
			return "trace/proRecord/proRecord_addjg";
		}
		
		return "trace/proRecord/proRecord_add";
	}
	
	
	/**
	 * 添加农事作业信息
	 * @param model
	 * @param leftdata
	 * @param datatype
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/add2.do" , method=RequestMethod.GET)
	public String add2(ModelMap model, String blockid, Integer linkType, HttpServletRequest request){
		model.put("blockid", blockid);
		model.put("linkType", linkType);
		
		ParkBlockPlantView plant = parkBlockPlantService.getCurrentPlantView(blockid);
		model.put("plant", plant);
		if(plant == null){
			model.put("errormessage", "该地块没有可用种植信息，请先到“种植管理”模块添加种植信息");
			return "sys/error/error";
		}
		
		if("1".equals(plant.getPlantType())){
			String cropName = cropsService.getCropFullname(plant.getCropid());
			if(cropName == null){
				cropName = plant.getCropName();
			}
			model.put("cropName", cropName);
			
			return "trace/proRecord/proRecord_add2";
		}else if("2".equals(plant.getPlantType())){
			String cropName = cropsyzService.getCropFullname(plant.getCropid());
			if(cropName == null){
				cropName = plant.getCropName();
			}
			model.put("cropName", cropName);
			
			return "trace/proRecord/proRecord_add2yz";
		}else if("3".equals(plant.getPlantType())){
			String cropName = cropsjgService.getCropFullname(plant.getCropid());
			if(cropName == null){
				cropName = plant.getCropName();
			}
			model.put("cropName", cropName);
			
			return "trace/proRecord/proRecord_add2jg";
		}
		
		return "trace/proRecord/proRecord_add2";
	}
	
	
	/**
	 * 保存农事作业信息
	 * @param proRecord
	 * @param result
	 * @param plantid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/save.json", method={RequestMethod.POST})
	@ResponseBody
	public Object save(@Valid ProRecord proRecord, BindingResult result, String plantid,
			String materialid, Double materialAmount, HttpServletRequest request){
		if(result.hasErrors()){
			return getSysErrors(result);
		}
		
		MyUploadFileParam uploadFileParam = new MyUploadFileParam(request);
		try {
			SysError info = proRecordService.add(proRecord, plantid, uploadFileParam, materialid, materialAmount, getLoginUser(request), request);
			return info;
		} catch (Exception e) {
			e.printStackTrace();
			return new SysError(e.getMessage());
		}
		
	}
	
	
	/**
	 * 修改农事作业信息
	 * @param model
	 * @param recordid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/edit.do" , method=RequestMethod.GET)
	public String edit(ModelMap model, String recordid, HttpServletRequest request){
		ProRecord proRecord = proRecordService.get(recordid);
		model.put("proRecord", proRecord);
		
		ParkBlockPlantView plant = parkBlockPlantService.getPlantView(proRecord.getParkBlockPlant().getPlantid());
		model.put("plant", plant);
		
		List<ProRecordImgs> list = proRecordImgsService.listRecordImgs(recordid);
		MyUploadFiles recordImgs = new MyUploadFiles();
		for(ProRecordImgs img : list){
			recordImgs.addFile(new MyUploadFile(img.getId(), img.getImgPath(), img.getImgName(), img.getImgDesc(), img.getThumb()));
		}
		model.put("recordImgs", recordImgs);
		
		model.put("linkType", proRecord.getLinkType());
		List<ProRecordMaterial> materials = proRecordMaterialService.listRecordMaterial(recordid);
		if(materials!=null && materials.size()>0){
			model.put("recordMaterial", materials.get(0));
		}
		
		if("1".equals(plant.getPlantType())){
			String cropName = cropsService.getCropFullname(plant.getCropid());
			if(cropName == null){
				cropName = plant.getCropName();
			}
			model.put("cropName", cropName);
			
			return "trace/proRecord/proRecord_edit";
		}else if("2".equals(plant.getPlantType())){
			String cropName = cropsyzService.getCropFullname(plant.getCropid());
			if(cropName == null){
				cropName = plant.getCropName();
			}
			model.put("cropName", cropName);
			
			return "trace/proRecord/proRecord_edityz";
		}else if("3".equals(plant.getPlantType())){
			String cropName = cropsjgService.getCropFullname(plant.getCropid());
			if(cropName == null){
				cropName = plant.getCropName();
			}
			model.put("cropName", cropName);
			
			return "trace/proRecord/proRecord_editjg";
		}
		
		return "trace/proRecord/proRecord_edit";
	}
	
	
	/**
	 * 保存修改的信息
	 * @param proRecord
	 * @param result
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/update.json", method={RequestMethod.POST})
	@ResponseBody
	public Object update(@Valid ProRecord proRecord, BindingResult result, String materialid, HttpServletRequest request){
		if(result.hasErrors()){
			return getSysErrors(result);
		}
		
		MyUploadFileParam uploadFileParam = new MyUploadFileParam(request);
		
		SysError info = proRecordService.update(proRecord, uploadFileParam, materialid, getLoginUser(request), request);
		return info;
	}
	
	
	/**
	 * 查看农事作业详情
	 * @param model
	 * @param recordid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/view.do" , method=RequestMethod.GET)
	public String view(ModelMap model, String recordid, HttpServletRequest request){
		ProRecord proRecord = proRecordService.get(recordid);
		model.put("proRecord", proRecord);
		
		ParkBlockPlantView plant = parkBlockPlantService.getPlantView(proRecord.getParkBlockPlant().getPlantid());
		model.put("plant", plant);
		
		if("1".equals(plant.getPlantType())){
			String cropName = cropsService.getCropFullname(plant.getCropid());
			if(cropName == null){
				cropName = plant.getCropName();
			}
			model.put("cropName", cropName);
			
			return "trace/proRecord/proRecord_view";
		}else if("2".equals(plant.getPlantType())){
			String cropName = cropsyzService.getCropFullname(plant.getCropid());
			if(cropName == null){
				cropName = plant.getCropName();
			}
			model.put("cropName", cropName);
			
			return "trace/proRecord/proRecord_viewyz";
		}else if("3".equals(plant.getPlantType())){
			String cropName = cropsjgService.getCropFullname(plant.getCropid());
			if(cropName == null){
				cropName = plant.getCropName();
			}
			model.put("cropName", cropName);
			
			return "trace/proRecord/proRecord_viewjg";
		}
		
		return "trace/proRecord/proRecord_view";
	}
	
	
	/**
	 * 删除
	 * @param model
	 * @param recordid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/deleteOne.do" , method=RequestMethod.GET)
	public String deleteOne(ModelMap model, String recordid, HttpServletRequest request){
		ProRecord proRecord = proRecordService.get(recordid);
		model.put("proRecord", proRecord);
		model.put("recordid", recordid);
		return "trace/proRecord/proRecord_deleteOne";
	}
	
	
	/**
	 * 删除一条记录
	 * @param recordid
	 * @param deleteType 删除类型：1清理数据、2错误数据（该类型将执行使用农资回收操作）
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/deleteOne.json", method={RequestMethod.POST})
	@ResponseBody
	public Object delete(String recordid, String deleteType, HttpServletRequest request){
		if(StringUtils.isEmpty(recordid)){
			return new SysError("没有选择任何信息.");
		}
		return proRecordService.deleteOne(recordid, deleteType, getLoginUser(request), request);
	}
	
	
//	/**
//	 * 删除农事作业信息
//	 * @param recordid
//	 * @param request
//	 * @return
//	 */
//	@RequestMapping(value="/delete.json", method={RequestMethod.POST})
//	@ResponseBody
//	public Object delete(String[] recordid, HttpServletRequest request){
//		if(recordid==null || recordid.length==0){
//			return new SysError("没有选择任何信息.");
//		}
//		return proRecordService.delete(recordid, getLoginUser(request), request);
//	}
	
	
	
//	/**
//	 * 上传农事作业图片
//	 * @param model
//	 * @param recordid
//	 * @param request
//	 * @return
//	 */
//	@RequestMapping(value="/addImgs.do" , method=RequestMethod.GET)
//	public String addImgs(ModelMap model, String recordid, HttpServletRequest request){
//		ProRecordView proRecord = proRecordService.getProRecordView(recordid);
//		model.put("proRecord", proRecord);
//		
//		String cropName = cropsService.getCropFullname(proRecord.getCropid());
//		if(cropName == null){
//			cropName = proRecord.getCropName();
//		}
//		model.put("cropName", cropName);
//		
//		List<ProRecordImgs> list = proRecordImgsService.listRecordImgs(recordid);
//		MyUploadFiles recordImgs = new MyUploadFiles();
//		for(ProRecordImgs img : list){
//			recordImgs.addFile(new MyUploadFile(img.getId(), img.getImgPath(), img.getImgName(), img.getImgDesc(), img.getThumb()));
//		}
//		model.put("recordImgs", recordImgs);
//		
//		return "trace/proRecord/proRecord_addImgs";
//	}
//	
//	
//	/**
//	 * 保存图片
//	 * @param recordid
//	 * @param fileName 文件名
//	 * @param origName 文件原名
//	 * @param fileDesc 文件描述
//	 * @param imgid 删除的图片
//	 * @param request
//	 * @return
//	 */
//	@RequestMapping(value="/saveImgs.json", method={RequestMethod.POST})
//	@ResponseBody
//	public Object saveImgs(String recordid, HttpServletRequest request){
//		
//		MyUploadFileParam uploadFileParam = new MyUploadFileParam(request);
//		
//		System.out.println(JsonUtil.toJSON(uploadFileParam));
//		
//		return proRecordImgsService.add(recordid, uploadFileParam, getLoginUser(request));
//	}
	
	
	
	@RequestMapping(value="/doexport.do", method=RequestMethod.GET)
	public String doexport(String plantType, String leftdata, String datatype, @DateTimeFormat(pattern="yyyy-MM-dd")Date begin,
			@DateTimeFormat(pattern="yyyy-MM-dd")Date end, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String parkid = null;
		String blockid = null;
		String filename = null;
		if(SystemCfg.UI_DATATYPE_PARK.equals(datatype)){
			parkid = leftdata;
			FarmPark farmPark = farmParkService.get(parkid);
			if(farmPark != null){
				filename = farmPark.getParkName();
			}
		}else if(SystemCfg.UI_DATATYPE_BLOCK.equals(datatype)){
			blockid = leftdata;
			ParkBlock parkBlock = parkBlockService.get(blockid);
			if(parkBlock != null){
				FarmPark farmPark = farmParkService.get(parkBlock.getFarmPark().getParkid());
				filename = farmPark.getParkName()+"-"+parkBlock.getBlockName();
			}
		}
		
		if(StringUtils.isEmpty(filename)){
			responseText("参数缺失，缺少园区或地块参数，导出失败。", response);
			return null;
		}
		
		String temps = null;
		if("1".equals(plantType)){
			temps = servletContext.getRealPath("/WEB-INF/excelTemps/prorecord_zz_export.xlsx");
		}
		
		if(StringUtils.isEmpty(temps)){
			responseText("参数错误，数据类型无效，导出失败。", response);
			return null;
		}
		
		File tempsFile = new File(temps);
		if(!tempsFile.isFile()){
			responseText("数据模板文件丢失，导出失败。", response);
			return null;
		}
		
		filename = filename + "-农事作业信息.xlsx";
		
		List<ProRecordView> list = proRecordService.listForExport(plantType, parkid, blockid, begin, end, getLoginUser(request));
		if(list == null){
			list = new ArrayList<>();
		}
		
		filename = java.net.URLEncoder.encode(filename, "UTF-8");
		response.resetBuffer();
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment; filename*=utf-8'zh_cn'" + filename);
		
		OutputStream outputStream = response.getOutputStream();
		ExcelUtil.exportExcel(tempsFile, outputStream, list);
		outputStream.close();
		return null;
	}
	
	
	//向响应写入文本
	protected void responseText(String text, HttpServletResponse response) throws Exception {
		response.resetBuffer();
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		out.write("<html><body>");
		out.write("<h2>"+text+"</h2>");
		out.write("</body></html>");
		out.close();
	}
	
}
